package daemon

import (
	"fmt"
	"time"

	"gitee.com/liumou_site/ssh-go-automatic-upgrade/internal/config"
	"go.uber.org/zap"
)

// Daemon 守护进程结构体
type Daemon struct {
	configFile    string
	pidFile       string
	logFile       string
	interval      time.Duration
	running       bool
	mirror        string
	installDir    string
	downloadDir   string
	force         bool
	upgradeTime   string
	skipTLSVerify bool
	
	// 依赖组件
	fileUtils     *FileUtils
	timeChecker   *TimeChecker
	upgradeService *UpgradeService
}

// NewDaemon 创建守护进程
// 示例值: configFile="/etc/ssh-upgrade/config.json", pidFile="/var/run/ssh-upgrade.pid", logFile="/var/log/ssh-upgrade.log", interval=1h
func NewDaemon(configFile, pidFile, logFile string, interval time.Duration, mirror, installDir, downloadDir string, force bool, upgradeTime string, skipTLSVerify bool) *Daemon {
	daemon := &Daemon{
		configFile:    configFile,
		pidFile:       pidFile,
		logFile:       logFile,
		interval:      interval,
		running:       false,
		mirror:        mirror,
		installDir:    installDir,
		downloadDir:   downloadDir,
		force:         force,
		upgradeTime:   upgradeTime,
		skipTLSVerify: skipTLSVerify,
	}
	
	// 初始化依赖组件
	daemon.initializeComponents()
	
	return daemon
}

// initializeComponents 初始化依赖组件
func (d *Daemon) initializeComponents() {
	d.fileUtils = NewFileUtils()
	d.timeChecker = NewTimeChecker(d.upgradeTime)
	d.upgradeService = NewUpgradeService(d.mirror, d.installDir, d.downloadDir, d.force, d.skipTLSVerify)
}

// Start 启动守护进程
// 示例值: 无参数
func (d *Daemon) Start() error {
	zap.L().Info("启动SSH升级守护进程")

	// 检查是否已经运行
	if d.isRunning() {
		return fmt.Errorf("守护进程已经在运行")
	}

	// 创建PID文件
	if err := d.fileUtils.CreatePIDFile(d.pidFile); err != nil {
		return fmt.Errorf("创建PID文件失败: %v", err)
	}

	// 设置信号处理
	d.setupSignalHandler()

	// 标记为运行状态
	d.running = true

	// 启动主循环
	go d.mainLoop()

	zap.L().Info("SSH升级守护进程启动成功")
	return nil
}

// Stop 停止守护进程
// 示例值: 无参数
func (d *Daemon) Stop() error {
	zap.L().Info("停止SSH升级守护进程")

	if !d.running {
		zap.L().Info("守护进程未运行")
		return nil
	}

	// 标记为停止状态
	d.running = false

	// 删除PID文件
	if err := d.fileUtils.RemovePIDFile(d.pidFile); err != nil {
		zap.L().Warn("删除PID文件失败", zap.Error(err))
	}

	zap.L().Info("SSH升级守护进程停止成功")
	return nil
}

// Status 获取守护进程状态
// 示例值: 无参数
func (d *Daemon) Status() (map[string]interface{}, error) {
	status := make(map[string]interface{})
	status["running"] = d.running
	status["config_file"] = d.configFile
	status["pid_file"] = d.pidFile
	status["log_file"] = d.logFile
	status["interval"] = d.interval.String()

	// 检查PID文件是否存在
	if d.fileUtils.IsProcessRunning(d.pidFile) {
		status["pid_file_exists"] = true
		if pid, err := d.fileUtils.ReadPIDFromFile(d.pidFile); err == nil {
			status["pid"] = pid
		}
	} else {
		status["pid_file_exists"] = false
	}

	return status, nil
}

// isRunning 检查守护进程是否在运行
func (d *Daemon) isRunning() bool {
	return d.fileUtils.IsProcessRunning(d.pidFile)
}

// setupSignalHandler 设置信号处理器
func (d *Daemon) setupSignalHandler() {
	// 信号处理逻辑已移动到daemon_manager.go中
}

// mainLoop 主循环
func (d *Daemon) mainLoop() {
	zap.L().Info("守护进程主循环开始")

	ticker := time.NewTicker(d.interval)
	defer ticker.Stop()

	// 立即执行一次检查
	d.upgradeService.CheckAndUpgrade()

	for d.running {
		select {
		case <-ticker.C:
			// 检查当前时间是否在允许的升级时间区间内
			if d.timeChecker.IsInUpgradeTimeWindow() {
				d.upgradeService.CheckAndUpgrade()
			} else {
				currentTime := time.Now().Format("15:04:05")
				zap.L().Info("当前时间不在升级时间区间内，跳过检查", zap.String("currentTime", currentTime))
			}
		}
	}

	zap.L().Info("守护进程主循环结束")
}

// 检查并升级SSH功能已移动到upgrade_service.go中

// RunDaemonLoop 运行守护进程主循环
// 示例值: args为命令行参数对象
func RunDaemonLoop(args interface{}) int {
	zap.L().Info("启动SSH自动升级守护进程")

	// 从args中提取配置参数
	var mirror, installDir, downloadDir, upgradeTime string
	var force bool
	var interval time.Duration

	// 尝试从config.Args类型中提取参数
	var skipTLSVerify bool
	if configArgs, ok := args.(*config.Args); ok {
		mirror = configArgs.Mirror
		installDir = configArgs.InstallDir
		downloadDir = configArgs.DownloadDir
		force = configArgs.Force
		skipTLSVerify = configArgs.SkipTLSVerify
		interval = time.Duration(configArgs.CheckInterval) * time.Hour
		upgradeTime = configArgs.UpgradeTime
	} else {
		// 使用默认值
		mirror = config.DefaultMirror
		installDir = config.DefaultInstallDir
		downloadDir = config.DefaultDownloadDir
		force = config.DefaultForce
		skipTLSVerify = config.DefaultSkipTLSVerify
		interval = time.Duration(config.DefaultCheckInterval) * time.Hour
		upgradeTime = config.DefaultUpgradeTime
	}

	// 创建守护进程实例
	daemon := NewDaemon(
		"/etc/ssh-upgrade/config.json",
		"/var/run/ssh-upgrade.pid",
		"/var/log/ssh-upgrade.log",
		interval,
		mirror,
		installDir,
		downloadDir,
		force,
		upgradeTime,
		skipTLSVerify,
	)

	// 启动守护进程
	if err := daemon.Start(); err != nil {
		zap.L().Error("守护进程启动失败", zap.Error(err))
		return 1
	}

	// 等待守护进程运行
	select {}
}
